package cci.siteMarchand.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cci.siteMarchand.dao.GenericDAO;
import cci.siteMarchand.model.DTOArticle;

public class ArticleDao extends GenericDAO<DTOArticle> {
	
	private GenreDao genreDao = new GenreDao();

	@Override
	public DTOArticle create(DTOArticle obj) {
		Connection con = null;
		PreparedStatement prepare = null;
		
		try {
			con = ds.getConnection();
			
			prepare = con.prepareStatement("INSERT INTO APP.ARTICLE(DESIGNATION, PRIX, DESCRIPTION, ID_GENRE, AUTEUR ) VALUES (?, ?, ?, ?, ?)");
			
			prepare.setString(1, obj.getDescription());
			prepare.setFloat(2, obj.getPrix());
			prepare.setString(3, obj.getDescription());
			prepare.setInt(4, obj.getGenre().getID());
			prepare.setString(5, obj.getAuteur());
			
			prepare.executeUpdate();
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}finally{
			try {
				if(prepare != null){
					prepare.close();
				}
				
				if(con != null){	
						con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}

		return obj;
	}

	@Override
	public DTOArticle update(DTOArticle obj) {
		delete(obj.getID());

		return create(obj);
	}

	
	@Override
	public String getTableName() {
		return "ADMIN.ARTICLE";
	}

	@Override
	public DTOArticle convertObjet(ResultSet result) throws SQLException {		
		DTOArticle obj = new DTOArticle();
		obj.setID(result.getInt(1));
		obj.setDesignation(result.getString(2));
		obj.setPrix(result.getFloat(3));
		obj.setDescription(result.getString(4));
		obj.setGenre(genreDao.find(result.getLong(5)));
		obj.setAuteur(result.getString(6));
		
		return obj;
	}
}
